/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.blog.web.extension;

import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.FileUploadLimitExceededException;
import net.sourceforge.stripes.exception.DefaultExceptionHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import foo.bar.blog.web.action.general.FileUploadLimitExceededActionBean;
import foo.bar.blog.web.action.general.UncaughtExceptionActionBean;
import foo.bar.blog.web.action.general.SecurityVerificationExceptionActionBean;
import foo.bar.blog.core.security.SecurityVerificationException;

/**
 * A custom excetpion handler that keeps the following information in the current http request attribute :-
 *
 * <ul>
 *  <li>stackTrace - the stack trace of the exception (in string)</li>
 * </ul>
 *
 * If it's a {@link net.sourceforge.stripes.controller.FileUploadLimitExceededException}, the following
 * extra http requst attributes are also available :-
 * <ul>
 *  <li>postedSize - the size of the attachment </li>
 *  <li>maxSize - the max size of attachment allowed</li>
 * </ul>
 *
 *
 * @author tmjee
 * @version $Date: 2009-07-05 10:12:59 +0000 (Sun, 05 Jul 2009) $ $Id$
 */
public class CustomExceptionHandler extends DefaultExceptionHandler {

    private static final Log LOG = LogFactory.getLog(CustomExceptionHandler.class);

    private Configuration configuration;

    public void init(Configuration configuration) throws Exception {
        this.configuration = configuration;
        super.init(configuration);
    }

    /**
     * Handle {@link net.sourceforge.stripes.controller.FileUploadLimitExceededException}.
     * 
     * @param e
     * @param request
     * @param response
     * @return
     */
    public Resolution handleFileUploadLimitExceededException(FileUploadLimitExceededException e, HttpServletRequest request, HttpServletResponse response) {
        LOG.error(e.toString(), e);
        HttpSession session = request.getSession(true);
            session.setAttribute("__stackTrace", stackTraceAsString(e));
            session.setAttribute("__postedSize", e.getPosted());
            session.setAttribute("__maxSize", e.getMaximum());
        return new RedirectResolution(FileUploadLimitExceededActionBean.class, "view");
    }


    /**
     * Handle all other exception.
     *
     * @param t
     * @param request
     * @param response
     * @return
     */
    public Resolution handleUncaughtedException(Throwable t, HttpServletRequest request, HttpServletResponse response) {
        LOG.error(t.toString(), t);
        HttpSession session = request.getSession(true);
        session.setAttribute("__stackTrace", stackTraceAsString(t));
        return new RedirectResolution(UncaughtExceptionActionBean.class, "view");
    }

    public Resolution handleSecurityVerificationException(SecurityVerificationException e, HttpServletRequest request, HttpServletResponse response) {
        LOG.warn(e.toString(), e);
        HttpSession session = request.getSession(true);
        session.setAttribute("__securityVerification", e.getMessage());
        session.setAttribute("__stackTrace", stackTraceAsString(e));
        return new RedirectResolution(SecurityVerificationExceptionActionBean.class, "view");
    }
    


    protected String stackTraceAsString(Throwable t) {
        StringWriter _writer = null;
        PrintWriter writer = null;
        try {
            _writer = new StringWriter();
            writer = new PrintWriter(_writer);
            t.printStackTrace(writer);
            return _writer.getBuffer().toString();
        }
        finally {
            if (_writer != null) {
                try {
                    _writer.close();
                } catch (IOException e) {
                }
            }
            if (writer != null) {
                writer.close();
            }
        }
    }


}
